#pragma once
#include "index.hpp"
#include "util.hpp"
#include <algorithm>
#include <jsoncpp/json/json.h>
#include "log.hpp"
namespace ns_searcher
{
    struct InvertedElemPrint
    {
        uint64_t doc_id;
        int weight;
        std::vector<std::string> words;
        InvertedElemPrint()
            :doc_id(0)
            ,weight(0)
        {}
    };
    class Searcher
    {
    public:
        Searcher(){}
        ~Searcher(){}
    public:
        void InitSearcher(const std::string& input)
        {
            //1.获取或者创建index对象
            index = ns_index::Index::GetInstance();
            //std::cout << "获取单例成功..." << std::endl;
            LOG(NORMAL, "获取单例成功...");
            //2.跟据index对象建立索引
            index->BuildIndex(input);
            //std::cout << "建立正排和倒排索引成功" << std::endl;
            LOG(NORMAL, "建立正排和倒排索引成功");
        }
        //1.query:搜索关键字 2.json_string:返回给用户浏览器的结果
        void Search(const std::string& query, std::string* json_string)
        {
            //1.[分词]对query按照seracher的要求进行分词
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            //2.[触发]跟据分词的各个词，进行index查找，建立index时就是忽略大小写，因此这里也忽略
            //std::vector<ns_index::InvertedElem> inverted_list_all; //输入字符串中所有单词的倒排拉链
            std::vector<InvertedElemPrint> inverted_list_all;
            std::unordered_map<uint64_t, InvertedElemPrint> tokens_map;

            for(std::string word : words)
            {
                boost::to_lower(word);
                ns_index::InvertedList* inverted_list = index->GetInvertedList(word); //一个单词的倒排拉链
                if(nullptr == inverted_list)
                {
                    continue; //文档中没有这个单词
                }
                //inverted_list_all.insert(inverted_list_all.end(), inverted_list->begin(), inverted_list->end());
                for(const auto& elem : *inverted_list)
                {
                    //item一定是doc_id相同的print节点
                    auto& item = tokens_map[elem.doc_id];
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(elem.word);
                }
            }
            for(const auto& item : tokens_map)
            {
                inverted_list_all.push_back(std::move(item.second));
            }
            //3.[合并排序]汇总查找结果，按照相关性weight降序
            // std::sort(inverted_list_all.begin(), inverted_list_all.end(), 
            //     [](const ns_index::InvertedElem& e1, const ns_index::InvertedElem& e2)
            //     {
            //         return e1.weight > e2.weight;
            //     }
            // );
            std::sort(inverted_list_all.begin(), inverted_list_all.end(), 
            [](const InvertedElemPrint& e1, const InvertedElemPrint& e2)
            {
                return e1.weight > e2.weight;
            }
        );
            //4.[构建]跟据查找出来的结果，构建json串---jsoncpp
            Json::Value root;
            for(auto& item : inverted_list_all)
            {
                ns_index::DocInfo* doc = index->GetForwardIndex(item.doc_id);
                if(nullptr == doc)
                {
                    continue;
                }
                Json::Value elem; 
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content, item.words[0]); //是去标签后的全部内容，但是我们只需要一部分
                elem["url"] = doc->url;
                //elem["id"] = (int)item.doc_id; //Json会把int强转为string,但是这里的doc_id为uint64_t
                //elem["weight"] = item.weight;
            
                root.append(elem); 
            }
            //Json::StyledWriter writer;
            Json::FastWriter writer; 
            *json_string = writer.write(root);
        }
        std::string GetDesc(const std::string& html_content, const std::string& word)
        {
            //找到word在html_content的首次出现，往前50字节，若没有从begin开始，往后找100字节，若没有，到end
            const std::size_t prev_step = 50;
            const std::size_t next_step = 100; 
            //1.找到首次出现
            //std::size_t pos = html_content.find(word); //在这里，html_content里面是大小写都有，而word里面全部早已被转为小写了，因此可能匹配不上
            // if (pos == std::string::npos)
            // {
            //    return "None1"; //其实不可能存在
            // }
            //这里使用search进行搜索
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), 
                                                [](int x, int y){return std::tolower(x) == std::tolower(y);});
            if(iter == html_content.end())
            {
                return "None1";
            }
            int pos = std::distance(html_content.begin(), iter);
            //2.获取start,end
            int start = 0;
            int end = html_content.size() - 1;
            if(pos > start + prev_step) //采用加法而不是减法，防止无符号整数减法产生更大的正数,也可以全部使用int类型
            {
                start = pos - prev_step;
            }
            if(pos + next_step < end)
            {
                end = pos + next_step;
            }
            //3.截取子串
            if(start >= end) return "None2";
            std::string desc =  html_content.substr(start, end - start);
            desc += "...";
            return desc;
        }
    private:
        ns_index::Index* index;
    };
}